import axios from '@/libs/api.request'
import axiosPreview from '@/libs/api.preview'
import { Spin, Message } from 'view-design'

const openBlobAppendix = (id) => {
  return axiosPreview.request({
    url: '/sys/appendix/downloadAppendix?id=' + id,
    method: 'get'
  })
}

const openBlobAppendixByUuid = (uuid) => {
  return axiosPreview.request({
    url: '/sys/appendix/download?uuid=' + uuid,
    method: 'get'
  })
}

const openAppendix = (id, uuid, readOnly) => {
  return axios.request({
    url: 'sys/appendix/open',
    method: 'post',
    data: { id: id, uuid: uuid, readOnly: readOnly }
  })
}

const openPic = (res) => {
  Spin.hide()
  let myWindow = window.open('', '')
  myWindow.document.write('<img style="-webkit-user-select: none;margin: auto;cursor: zoom-in;" src="' + URL.createObjectURL(res) + '">')
  myWindow.focus()
  myWindow.document.body.style.margin = '0px'
  myWindow.document.body.style.padding = '0px'
  URL.revokeObjectURL(res)
}

const openText = (res) => {
  Spin.hide()
  let reader = new FileReader()
  reader.onload = function (e) {
    Spin.hide()
    let myWindow = window.open('', '')
    myWindow.document.write(reader.result)
    myWindow.focus()
  }
  reader.readAsText(res)
}

const openPdf = (res) => {
  Spin.hide()
  let reader = new FileReader()
  reader.onload = function (e) {
    Spin.hide()
    let myWindow = window.open('', '')
    myWindow.document.write('<embed width="100%" height="100%" name="plugin" id="plugin" src="' + reader.result + '" type="application/pdf" internalinstanceid="5">')
    myWindow.focus()
  }
  reader.readAsDataURL(res)
}

export const previewFile = (id, name, uuid, readOnly) => {
  Spin.show()
  // 使用自带打开office
  let suffix = name.substring(name.lastIndexOf('.') + 1, name.length)
  if (suffix === 'jpg' || suffix === 'png' || suffix === 'jpeg') {
    if (id === null) {
      openBlobAppendixByUuid(uuid).then(res => {
        Spin.hide()
        openPic(res)
      })
    } else {
      openBlobAppendix(id).then(res => {
        Spin.hide()
        openPic(res)
      })
    }
  } else if (suffix === 'doc' || suffix === 'docx' || suffix === 'xls' || suffix === 'xlsx' || suffix === 'ppt' || suffix === 'pptx') {
    openAppendix(id, uuid, readOnly).then(res => {
      if (res.code === 200) {
        window.location.href = res.data
      }
      Spin.hide()
    })
  } else if (suffix === 'txt') {
    if (id === null) {
      openBlobAppendixByUuid(uuid).then(res => {
        openText(res)
      })
    } else {
      openBlobAppendix(id).then(res => {
        openText(res)
      })
    }
  } else if (suffix === 'pdf') {
    if (id === null) {
      openBlobAppendixByUuid(uuid).then(res => {
        openPdf(res)
      })
    } else {
      openBlobAppendix(id).then(res => {
        openPdf(res)
      })
    }
  } else {
    Spin.hide()
    Message.error('文件不自持在线查看')
  }
}
